package test.CPU;

import javax.swing.*;
import java.awt.*;

public class CPUPanel extends JPanel implements CPUObserver{
    public static CPUPanel instance = new CPUPanel();

    private JLabel clockLabel;
    private JTextField speedTextField;
    private JButton updateButton;
    private CPUController cpuController;

    public static CPUPanel getInstance() {
        return instance;
    }

    private CPUPanel() {
        cpuController = CPUController.getInstance();
        //添加观察者
        CPUController.addObserver(this);

        // 初始化 JLabel，用于显示 cpuClock 的值
        clockLabel = new JLabel("CPU Clock: 0");
        clockLabel.setFont(new Font("Arial", Font.PLAIN, 24));

        // 初始化 JTextField 和 JButton
        speedTextField = new JTextField("1.0", 5); // 默认值为1秒
        updateButton = new JButton("更新");

        // 添加按钮监听器，读取文本框的值并更新速率
        updateButton.addActionListener(e -> {
            try {
                double delay = Double.parseDouble(speedTextField.getText().trim());
                if (delay > 0) {
                    cpuController.setUpdateRate(delay);
                } else {
                    JOptionPane.showMessageDialog(this, "请输入正数");
                }
            } catch (NumberFormatException ex) {
                JOptionPane.showMessageDialog(this, "不合法的输入，请输入正数");
            }
        });

        // 创建一个面板，用来放置输入框和按钮
        JPanel inputPanel = new JPanel();
        inputPanel.add(new JLabel("更新速率（秒）"));
        inputPanel.add(speedTextField);
        inputPanel.add(updateButton);

        // 布局设置
        this.setLayout(new BorderLayout());
        this.add(clockLabel, BorderLayout.CENTER);
        this.add(inputPanel, BorderLayout.SOUTH);
    }

    public static void main(String[] args) {
        // 设置窗口
        JFrame frame = new JFrame("CPU Clock Viewer");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(400, 200); // 适当加宽以容纳输入框和按钮
        frame.setContentPane(CPUPanel.getInstance()); // 使用单一实例
        frame.setVisible(true);
    }

    @Override
    public void CPUUpdate(int clock) {
        // 在 EDT 线程中更新 UI
        SwingUtilities.invokeLater(() -> {
            clockLabel.setText("CPU Clock: " + clock);
        });
    }
}
